package org.ainlolcat.ainscience.entity;

import org.ainlolcat.ainscience.UpdateListener;
import org.ainlolcat.ainscience.column.Column;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ainlolcat
 * Date: 10/30/11
 */
public class EntityTableModel implements TableModel, UpdateListener {
    Entity entity;
    List<TableModelListener> listeners;
    public EntityTableModel(Entity entity){
        this.entity = entity;
        listeners = new ArrayList<TableModelListener>();
    }

    public int getRowCount() {
        return entity.getRowCount();
    }

    public int getColumnCount() {
        return entity.getColumnCount();
    }

    public String getColumnName(int i) {
        return entity.getColumnByOrder(i).getName();
    }

    public Class<?> getColumnClass(int i) {
        //if (entity.getColumnByOrder(i).getType()== MatrixFileParser.MATRIX_DELIMETER_TYPE_DOUBLE) return Double.class;
        //if (entity.getColumnByOrder(i).getType()== MatrixFileParser.MATRIX_DELIMETER_TYPE_INTEGER) return Integer.class;
        return String.class;
    }

    public boolean isCellEditable(int i, int i1) {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public Object getValueAt(int row, int column) {
        Column c = entity.getColumnByOrder(column);
        if (c==null) return null;
        if (c.getValue(row)==null) return null;
        return c.getValue(row).toString();
    }

    public void setValueAt(Object o, int i, int i1) {
        throw new UnsupportedOperationException();
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void addTableModelListener(TableModelListener tableModelListener) {
        if (!listeners.contains(tableModelListener)){
            listeners.add(tableModelListener);
        }
    }

    public void removeTableModelListener(TableModelListener tableModelListener) {
        if (listeners.contains(tableModelListener)){
            listeners.remove(tableModelListener);
        }
    }

    public void onProjectUpdate() {
        for (TableModelListener tml: listeners){
            tml.tableChanged(new TableModelEvent(this));
        }
    }

    public void onEntityUpdate(Entity entity, int action) {
        for (TableModelListener tml: listeners){
            tml.tableChanged(new TableModelEvent(this));
        }
    }

}
